package permission

import (
	"context"
	"errors"
	"fmt"
	"github.com/fatih/color"
	"github.com/ifnk/micro-blog/internal/pkg/dbcontext"
	"github.com/ifnk/micro-blog/internal/pkg/log"
	"github.com/ifnk/micro-blog/internal/pkg/utils"
	"github.com/ifnk/micro-blog/protobuf/permission_pb"
	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
)

// user 服务  内部实现(controller )
func NewUserServer(logger *log.Logger, repo Repository, db *dbcontext.GormDB, jinzhuDB *dbcontext.JinZhuDB) Server {
	return Server{
		logger:                   logger,
		repo:                     repo,
		db:                       db,
		UserServiceDefaultServer: permission_pb.UserServiceDefaultServer{DB: jinzhuDB.DB},
	}
}

type Server struct {
	permission_pb.UserServiceDefaultServer // 这个名字不要瞎换 就要 grpc gorm 生成的这个 server 名字
	logger                                 *log.Logger
	repo                                   Repository
	db                                     *dbcontext.GormDB
}

// 这里是除Crud 以外自己定义的方法
func (s *Server) TestDuDu(ctx context.Context, in *permission_pb.CreateUserRequest) (*permission_pb.CreateUserResponse, error) {
	color.Blue("123 -> %+v", 123)
	out := &permission_pb.CreateUserResponse{}
	return out, nil
}
func (s *Server) Register(ctx context.Context, in *permission_pb.CreateUserRequest) (*permission_pb.CreateUserResponse, error) {
	u, err := in.GetPayload().ToORM(ctx)
	var count int64
	err = s.db.Model(&permission_pb.UserORM{}).Where("username = ?", u.Username).Count(&count).Error
	if err != nil {
		return nil, err
	}
	if count > 0 {
		return nil, errors.New("用户名已注册")
	}

	// 否则 附加uuid 密码md5简单加密 注册
	u.Password = utils.MD5V([]byte(u.Password))
	u.UUID = uuid.NewV4()
	err = s.db.Create(&u).Error

	if err != nil {
		return nil, errors.New(fmt.Sprintf("创建用户失败 -> %+v", err))
	}
	// 默认给个系统角色
	err = s.db.Create(&permission_pb.UserRltAuthorityORM{AuthorityId: 888, UserId: u.Id}).Error
	if err != nil {
		return nil, errors.New(fmt.Sprintf("给用户 默认 角色 失败 -> %+v", err))
	}

	pb, err := u.ToPB(ctx)
	return &permission_pb.CreateUserResponse{Result: &pb}, err
}
func (s *Server) ChangePassword(ctx context.Context, in *permission_pb.ChangePasswordRequest) (*permission_pb.CreateUserResponse, error) {
	var user permission_pb.UserORM
	newPassword := in.GetNewPassword()
	u, err := in.GetPayload().ToORM(ctx)
	u.Password = utils.MD5V([]byte(u.Password))

	err = s.db.Where("username = ? AND password = ?", u.Username, u.Password).First(&user).Update("password", utils.MD5V([]byte(newPassword))).Error
	pb, _ := user.ToPB(ctx)
	return &permission_pb.CreateUserResponse{Result: &pb}, err
}
func (s *Server) GetUserByName(ctx context.Context, in *permission_pb.GetUserByNameRequest) (*permission_pb.GetUserByNameResponse, error) {
	name := in.GetPayload()
	var user permission_pb.UserORM
	// todo 这里关联查询 带不出来 角色 列表 数据 ，后面 有空捣鼓下
	err := s.db.Where("username = ?", name).Preload("Authorities").First(&user).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("用户名不存在")
	}
	pb, err := user.ToPB(ctx)
	return &permission_pb.GetUserByNameResponse{Result: &pb}, err
}

func (s *Server) Update(ctx context.Context, in *permission_pb.UpdateUserRequest) (*permission_pb.UpdateUserResponse, error) {
	orm, _ := in.Payload.ToORM(ctx)
	err := s.db.Updates(&orm).Error
	pb, _ := orm.ToPB(ctx)
	return &permission_pb.UpdateUserResponse{Result: &pb}, err
}
